package com.roc.web.action.terminal;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.roc.dao.DaoException;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TermVer;
import com.roc.service.IExcelService;
import com.roc.service.ServiceException;
import com.roc.service.term.TermVerService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@Component
@Namespace("/termVer")
@SuppressWarnings("serial")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class TermVerManageAction extends PaginationBaseAction{
	
	private Logger logger = LogManager.getLogger(TermVerManageAction.class);
	
	private TermVerManageSearchCondition searchCondition;
	
	
  
    @Autowired
    private TermVerService termVerService;
    @Autowired
    private IPageService pageService;
    @Autowired
    private IExcelService excelService;
    @Autowired
	IPageService pagenitionService;
    
    private TermVer termVer;
    
/**
 * 初始化页面
 * @return
 * @throws Exception
 */
    @Action(value = "init", results = { @Result(name = "success", location = "/pages/terminal/TermVerManage.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })	
	public String init() throws Exception{
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		/*if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())|| op.getRoleType().equals(Role.SYSTEM.getCode()))
		{*/
			return SUCCESS;
		/*}
		addActionError("无权限访问!!!");
		return ERROR;*/	
	}
    /**
	 * 添加初始化页面
	 * @return
	 */
    @Action(value = "insertTermVer", results = { @Result(name = "success", location = "/pages/terminal/AddModifyTermVerManage.jsp")
    })	
	public String insertTermVer()throws Exception
	{
		return SUCCESS;
	}
    
    
    
    @Action(value="valiareaCodeTerm")
	public void validateArea()
	{
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		try {
			boolean value = termVerService.isExistName(termVer);
			response.getWriter().print(value);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			addActionError("验证区域名称错误!!!");
		} 
	}
    
    
    
    
    
    /**
     * 查询
     * @return
     */
    @Action(value = "queryTermVerManage", results = { @Result(name = "success", location = "/pages/terminal/TermVerManage.jsp")
    })	
	public String queryTermVerManage()throws Exception{
    	
    	
		 Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())|| op.getRoleType().equals(Role.SYSTEM.getCode()))
			{
				logger.info("查询终端版本管理");
	    		try {
	    			if(searchCondition==null){
	    				searchCondition=(TermVerManageSearchCondition)getSearchConditionFromSession();
	    				if(searchCondition==null){
	    					searchCondition=new TermVerManageSearchCondition();
	    				}
	    			}
	    			searchCondition.setOpId(String.valueOf(op.getId()));//获取当前人员ID 
	    			
	    			int rows=pagenitionService.countSQL(searchCondition);
	    			if(rows>0){
	    				searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
	    			}
	    			List<TermVer> termVerManageList = new ArrayList<TermVer>();
	    			dealWith(termVerManageList,searchRsList);
	    			
	    			getRequest().setAttribute("termVerManageList", termVerManageList);
	    			this.setTotalPage(this.calcuTotalPage(rows));
	    			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
	    			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
	    			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
	    			addActionMessage("当前条件下统计到【"+rows+"】条记录");
	    			
	    		} catch (Exception e) {
	    			
	    			logger.error(e.getMessage(),e);
	    			addActionError(e.getMessage());
	    			return ERROR;
	    		}		
	    	   return SUCCESS;
			}
			addActionError("无权限访问!!!");
			return ERROR;	
		}
		 
   
	
	/**
	 * 添加
	 * @Title: addBlackLists
	 * @Description: TODO
	 * @param @return    
	 * @return String    
	 * @throws
	 */
    @Action(value = "insertTermVerManage", results = { @Result(name = "success", 
    		location = "/pages/terminal/TermVerManage.jsp")})	
	public String insertTermVerManage()
	{
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
			resultMap=termVerService.insertTermVerManage(termVer, logingMerchant);
			
			if(resultMap.size()>0){
				addActionMessage((String) resultMap.get("result"));
				
			}
			queryTermVerManage();
		} catch (Exception e) {
			e.printStackTrace();
			addActionError("添加终端管理失败~");
		}
		return SUCCESS;		
	}
    
   
    /**
     * 根据id查询
     * @return
     */
    @Action(value = "updateTermVerById", results = { @Result(name = "success", location = "/pages/terminal/AddModifyTermVerManage.jsp")
    })	
    public String updateTermVerById()throws Exception{
    	Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
    	logger.info("根据id查询终端版本管理");
    	try {
    		termVer=termVerService.updateTermVerById(termVer.getId());
    		termVer.setId(termVer.getId());
    		termVer.setManufacturer(termVer.getManufacturer());
    		termVer.setModelId(termVer.getModelId());
    		termVer.setVersionId(termVer.getVersionId());
    		termVer.setIssueTs(termVer.getIssueTs());
    		termVer.setIsValId(termVer.getIsValId());
    		getRequest().setAttribute("flag", "update");
    	} catch (DaoException e) {
    		
    		logger.error(e.getMessage(),e);
    		addActionError(e.getMessage());
    		return ERROR;
    	}		
    	return SUCCESS;
    	
    }
    
	/**
	 * 修改
	 * @Title: addBlackLists
	 * @Description: TODO
	 * @param @return    
	 * @return String    
	 * @throws
	 */
    @Action(value = "updatetTermVerManage", results = { @Result(name = "success", 
    		location = "/pages/terminal/TermVerManage.jsp")})	
	public String updatetTermVerManage()
	{
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
			resultMap=termVerService.updateTermVerManage(termVer, logingMerchant);
			
			if(resultMap.size()>0){
				addActionMessage((String) resultMap.get("result"));
				
			}
		queryTermVerManage();
		} catch (Exception e) {
			e.printStackTrace();
			addActionError("修改终端管理失败~");
		}
		return SUCCESS;		
	}
	/**
	 * 删除
	 * @Title: addBlackLists
	 * @Description: TODO
	 * @param @return    
	 * @return String    
	 * @throws
	 */
    @Action(value = "deleteTermVerManage", results = { @Result(name = "success", 
    		location = "/pages/terminal/TermVerManage.jsp")})	
	public String deleteTermVerManage()
	{
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		try {
			Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
			resultMap=termVerService.deleteTermVerManage(termVer, logingMerchant);
			
			if(resultMap.size()>0){
				addActionMessage((String) resultMap.get("result"));
				
			}
			queryTermVerManage();
		} catch (Exception e) {
			e.printStackTrace();
			addActionError("删除终端管理失败~");
		}
		return SUCCESS;		
	}
	
	
	
	
/**
 * 根据查询得到的list，封装到TermVerManageBean
 * @param revList
 * @param searchRsList
 * @return
 * @throws ServiceException
 */

	private List<TermVer> dealWith(List<TermVer> termVerManageList,List<Object> searchRsList) throws ServiceException {
		if(searchRsList!=null&&searchRsList.size()>0)
		{
			Iterator<?> iterator=searchRsList.iterator();
			while(iterator.hasNext())
			{
				Object[] obj=(Object[]) iterator.next();
				TermVer tvm=new TermVer();

				tvm.setId(Integer.valueOf(String.valueOf(Constance.Null2EmptyTrim(obj[0]))));
				tvm.setManufacturer(Constance.Null2EmptyTrim(obj[1]));
				tvm.setModelId(Constance.Null2EmptyTrim(obj[2]));
				tvm.setVersionId(Constance.Null2EmptyTrim(obj[3]));
				tvm.setIssueTs(Constance.Null2EmptyTrim(obj[4]));
				String state=Constance.Null2EmptyTrim(obj[5]);
				if(state.equals("0")){
					state="无效";
				}else if(state.equals("1")){
					state="有效";
				}
				tvm.setIsValId(state);//是否有效
				tvm.setOpId((Constance.Null2EmptyTrim(obj[6])));
				 termVerManageList.add(tvm);
			}
		}
		return termVerManageList;
	}



	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {

		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {

		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {

		getSession().setAttribute(SEARCH_SESSION_TERM_VER_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {

		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_TERM_VER_QUERY);
	}

	@Override
	protected String getInitPageSize() {

		return Constance.PAGE_MAX_SIZE+"";
	}
	


	public TermVerManageSearchCondition getSearchCondition() {
		return searchCondition;
	}


	public void setSearchCondition(TermVerManageSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}


	public TermVer getTermVer() {
		return termVer;
	}
	public void setTermVer(TermVer termVer) {
		this.termVer = termVer;
	}
	
	
	
	
}
